//
//  CZComposeTextView+Extension.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
extension CZComposeTextView {

			var emticonText: String {
	get {
	//获取表情文本附件
	//在指定范围内 遍历副文本的属性
	var result = ""
	self.attributedText.enumerateAttributesInRange( NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) in
	if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
	//就是文本附件
	let chs = attachment.emoticon?.chs!
	result += chs!
	} else {
	//文本
	let text = self.attributedText.attributedSubstringFromRange(range).string
	result += text
	}
	}
	return result
	}
	}
	
	func insertEmticon(emoticon: CZEmoticon, fontSize: UIFont) {
		//获取表情副文本对应字符串

		if emoticon.type == "0" {
			//			textView.insertText(emoticon.chs!)
			//记录上一次的副文本
			let orginaAttr = NSMutableAttributedString(attributedString: self.attributedText)
			
			//1.根据表情图片路径创建一个 uiimage
			let image = UIImage(named: emoticon.path!)
			// 2.根据 uiiimage 创建一个 NSTextAttachment() 文本附件
			let attachtment = CZTextAttachment()
			attachtment.image = image
			
			
			//取到字体的高度
			let fontHeight = fontSize.lineHeight
			
			attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
			//3 根据NSTextAttachment创建一个NSAttributedString副文本
			let attr = NSAttributedString(attachment: attachtment)
			//获取 textview的选中范围
			var range = self.selectedRange
			//替换选中的字符串
			orginaAttr.replaceCharactersInRange(range, withAttributedString: attr)
			
			//追加副文本
			//orginaAttr.appendAttributedString(attr)
			//设置副文本的字体大小
			orginaAttr.addAttribute(NSFontAttributeName, value: fontSize, range: NSMakeRange(0, orginaAttr.length))
			
	
			
			self.attributedText = orginaAttr
			//每次点击表情开始位置+1
			range.location += 1
			//设置选中范围长度为0
			range.length = 0
			//设置选中范围
			self.selectedRange = range
			//		发送文字改变的通知
			NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
			//自己调用代理
			self.delegate?.textViewDidChange?(self)
			
			
		} else {
			self.insertText((emoticon.code! as NSString).emoji()!)
			
		}
	}

}





















